import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {connect} from 'react-redux'
import Skeleton from 'taro-skeleton';
import {View, Navigator, Icon, Image, Text, Block} from '@tarojs/components'
import {AtIcon} from 'taro-ui'
import {http} from '../../utils/http'
import {
  LIST_CATEGORY,
  USER_SALE_SUB,
  OFF_USER_SALE_SUB,
  TARO_ENV,
  SCAN_BIND_SELLER,
  IDENTITY_IS_SELLER
} from '../../constants/api'
import fetchNewGoodsList from "../../utils/fetchNewGoodsList";
import {
  SubCategory,
  LimitGood as LimitGoodType,
  PlatformSet
} from '../../utils/server.interface'
import {autoLocation, setCity} from '../../actions/location'
import {platform} from '../../utils/platform-settting.service'
import {getHeadTop, limitedParams, vcmonitor, clearSearch as clearSearchFunc} from '../../utils/tools'
import CountDown1 from '../../components/count-down/count-down-1'
import {user} from '../../utils/user.service'
import {location as localtionServer} from '../../utils/location.service';
import SupportBar from '../../components/support-bar/support-bar'
import Headercar from "../components/header-car/header-car";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import Advertisement from '../../components/advertisement/advertisement'
import GoodsBigImgList from "../../components/goods-big-img-list/goods-big-img-list";
import Share from "../../components/share/share";
import AdvertisementMember from "../../components/advertisement/member"
import { getMemberAdvertisement } from '../../utils/getCommonData';
import './index.scss'
import CustomTabBar from "../../components/tabBar/tab-bar";

interface StateType {
  searchBarTop: number
  linkUri: string
  searchText: string
  memberAdvertisement: any
  type: 0 | 1 | 2 | 3
  categoryId: number
  categorys: SubCategory[]
  goods: LimitGoodType[]
  loadMoreStatus: "more" | "loading" | "noMore"
  platformSet?: PlatformSet
  isClose: boolean
  isUser: boolean
  loading: boolean
  tabBarInfo: any
}

type PageState = {}

@connect(({location}) => ({
  location
}), (dispatch) => ({
  setCity(city) {
    dispatch(setCity(city))
  },
  autoLocation(city) {
    dispatch(autoLocation(city))
  }
}))

class limitedIndex extends Component {
  state: StateType = {
    searchBarTop: 0,
    searchText: '',
    memberAdvertisement: '',
    type: 0,
    categoryId: 0,
    categorys: [],
    goods: [],
    loadMoreStatus: "loading",
    linkUri: '',
    isClose: true,
    isUser: true,
    loading: true,
    tabBarInfo: false
  }

  async UNSAFE_componentWillMount() {
    await localtionServer.autoLocation()
    const headTop = getHeadTop()
    const searchBarTop = headTop.statusBar > 20 ? (headTop.statusBar + headTop.top + 30) : (headTop.statusBar + headTop.top + 40)
    this.setState({searchBarTop})
    let category = Taro.getCurrentInstance().router.params.category || 0
    if (!category) {
      if (limitedParams.params.length > 0) {
        limitedParams.params.map(item => {
          if (item[0] === 'category') category = item[1]
        })
        limitedParams.params = []
      }
    }
    let categoryArr: SubCategory[] = []
    const categoryRet = await http.get<SubCategory[]>(LIST_CATEGORY, {type: 0})
    if (!categoryRet) {
      return false
    }
    categoryArr = categoryRet
    const goods = await this.getGoodsData(this.page)
    const platformSet = await platform.getSetting()
    if (platformSet) {
      this.setState({
        categoryId: category,
        categorys: categoryArr,
        platformSet,
        goods,
        loading: false
      })
    } else {
      this.setState({
        categoryId: category,
        categorys: categoryArr,
        goods,
        loading: false,
        platformSet: platform
      })
    }
  }

  async componentDidShow() {
    platform.getIndexNavigation().then(res => {
      if (res) {
        const tabBarInfo = JSON.parse(res)
        this.setState({ tabBarInfo })
      }
    })
    clearSearchFunc()
    vcmonitor(this)
    this.shareParams = await user.getSellerParams()
    let link = '/pages/limited/index?' + this.shareParams
    if (process.env.TARO_ENV === 'h5') {
      link = window.location.origin + link
      const shareData = {
        title: platform.info.platformName,
        desc: '限时抢购',
        link,
        imgUrl: platform.info.platformLogo
      }
      h5Wx.share(shareData)
    } else {
      link += `&sKey=${Taro.getStorageSync('sKey' || '')}`
    }
    let isUser = true
    if (process.env.DISTINGUISH_IDENTITY) {
      const identityIsSeller = await http.get(IDENTITY_IS_SELLER, {})
      isUser = !identityIsSeller.isSeller
    }
    this.setState({ linkUri: link, isUser, memberAdvertisement: await getMemberAdvertisement({ position: 'qianggou' }) })
    const bindSellerId = Taro.getCurrentInstance().router.params.bindSellerId || ''
    const tempSellerId = Taro.getCurrentInstance().router.params.tempSellerId || ''
    if ((bindSellerId || tempSellerId) && process.env.DISTINGUISH_IDENTITY) {
      http.HPost(SCAN_BIND_SELLER, { temp_seller_id: tempSellerId, refer_seller_id: bindSellerId });
    }
    const {loading} = this.state
    if (this.page == 1 && !loading) {
      const goods = await this.getGoodsData(this.page)
      this.setState({goods})
    }
  }

  shareParams = ''
  page = 1

  onShareAppMessage() {
    return {
      title: platform.info.platformName,
      path: '/pages/limited/index?' + this.shareParams + `&sKey=${Taro.getStorageSync('sKey' || '')}`
    }
  }

  onShareTimeline() {
    return {
      title: "限时抢购",
      query: this.shareParams + `&sKey=${Taro.getStorageSync('sKey' || '')}`
    }
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const old = this.state.goods
      const goods = await this.getGoodsData(++this.page)
      this.setState({goods: [...old, ...goods]})
    }
  }

  async getGoodsData(page = 1) {
    const {searchText, categoryId, type} = this.state
    const id = type === 0 ? categoryId : 0
    const dataType = type === 0 ? 0 : 1
    const params = {
      module_type: "4",
      order_rule: 4,
      is_qianggou: 1,
      data_type: dataType,
      page: page,
      length: 10,
      key_word: searchText,
      // region_region: this.props.location.region_id,
      region_region: "",
      region_category: id === 0 ? "" : id,
    };
    if(dataType === 0) params.is_not_start = 0;
    if(dataType === 1) params.is_not_start = 1;
    // 商品列表
    const ret = await fetchNewGoodsList.getGoodsList(params);
    if (ret && Array.isArray(ret)) {
      if (ret.length === 10) {
        this.setState({loadMoreStatus: 'more'})
      } else {
        this.setState({loadMoreStatus: 'noMore'})
      }
      return ret
    } else {
      this.setState({loadMoreStatus: 'noMore'})
      return []
    }
  }

  async onPullDownRefresh() {
    this.page = 1
    this.setState({loadMoreStatus: 'loading', goods: []}, async () => {
      const goods = await this.getGoodsData(this.page)
      this.setState({goods}, () => {
        Taro.stopPullDownRefresh()
      })
    })
  }

  clearSearch() {
    this.page = 1
    this.setState({searchText: ''}, async () => {
      const goods = await this.getGoodsData(this.page)
      this.setState({goods})
    })
  }

  async searchClick() {
    this.page = 1
    this.setState({loadMoreStatus: 'loading', goods: []}, async () => {
      const goods = await this.getGoodsData(this.page)
      this.setState({goods})
    })
  }

  searchInput(value) {
    this.setState({searchText: value})
  }

  categoryClick(id) {
    this.page = 1
    this.setState({categoryId: id, loadMoreStatus: 'loading', goods: []}, async () => {
      const goods = await this.getGoodsData(this.page)
      this.setState({goods})
    })
  }

  typeChange(type) {
    this.page = 1
    if (this.state.loadMoreStatus !== 'loading') {
      this.setState({type, loadMoreStatus: 'loading', goods: []}, async () => {
        const goods = await this.getGoodsData(this.page)
        this.setState({goods})
      })
    }
  }

  async getMSG(index, e) {
    e.stopPropagation()
    const isLogin = await user.checkLogin();
    if (!isLogin) {
      user.jumpLogin()
      return
    }
    const {goods, platformSet} = this.state
    const that = this
    const uuid = goods[index].uuid
    try {
      const tmplIds = platformSet.saleMessageTemplateId || []
      const acceptAry = []
      Taro.requestSubscribeMessage({
        tmplIds,
        success(res) {
          tmplIds.map((item) => {
            if (res[item] == 'accept') {
              acceptAry.push(item)
            }
          })
          if (acceptAry.length > 0) {
            http.post(USER_SALE_SUB, {goodsUUID: uuid, templateIds: acceptAry.join(",")})
            goods[index]['is_subscribe'] = 1
            that.setState({goods})
          }

        },
        fail(error) {
          Taro.showModal({
            title: '提示',
            content: '为了提供更好的服务，建议您开启订阅消息',
            success: (res) => {
              if (res.confirm) {
                Taro.openSetting()
              }
            }
          })
          console.log(error)
        }
      })
    } catch (e) {
      Taro.showModal({
        title: '提示',
        content: '为了提供更好的服务，建议您开启订阅消息',
        success: (res) => {
          if (res.confirm) {
            Taro.openSetting()
          }
        }
      })
      console.log(e)
    }
  }

  async removeMSG(index, e) {
    e.stopPropagation()
    const {goods} = this.state
    const that = this
    const uuid = goods[index].uuid
    const ret = await http.postCar(OFF_USER_SALE_SUB, {goodsUUID: uuid})
    if (ret == '取消成功') {
      goods[index]['is_subscribe'] = 0
      that.setState({goods})
    }
  }

  coutEnd(index) {
    const {goods} = this.state
    goods[index]['can_buy'] = 1
    this.setState({goods})
  }

  goDetail(url) {
    Taro.navigateTo({
      url
    })
  }

  render() {
    const {
      linkUri,
      loading,
      searchBarTop,
      type,
      isUser,
      categorys,
      categoryId,
      goods,
      loadMoreStatus,
      platformSet,
      memberAdvertisement,
      tabBarInfo,
      isClose
    } = this.state
    return (
      <View className='root limitedRoot otherLimitedRoot'>
        {tabBarInfo && <View style='position: fixed; width: 100%; z-index: 9999; bottom: 0px; left: 0;'><CustomTabBar pagePath='pages/limited/index' isBigIndexPage={false} tabBarInfo={tabBarInfo} /></View>}
        <View>
          <GzhAuth />
          <View className='head-bg' style={`min-height: ${TARO_ENV !== 'h5' && TARO_ENV !== 'tt' && searchBarTop}Px;`}>
            {TARO_ENV !== 'h5' && TARO_ENV !== 'tt' && <Headercar color='#333' />}
            <View className='type-box' style={`padding-top:${TARO_ENV !== 'h5' &&  TARO_ENV !== 'tt' && searchBarTop}Px;`}>
              <View className={`type-item ${type === 0 && 'selected'}`}
                onClick={this.typeChange.bind(this, 0)}
              >正在疯抢</View>
              <View className={`type-item ${type === 1 && 'selected'}`}
                onClick={this.typeChange.bind(this, 1)}
              >即将开抢</View>
              <View className={`active-bar ${type === 1 && 'two'} ${type === 3 && 'three'}`} />
            </View>
            {type === 0 && categorys && categorys.length > 0 && <View className='label-nav'>
              <View className={`nav-box ${!isClose && 'nav-box-open'}`}>
                <View className={`item ${0 == categoryId ? 'active' : ''}`}
                  onClick={this.categoryClick.bind(this, 0)}
                >全部</View>
                <View className='subcategory'>
                  {categorys.map(item => <View key={item.id}
                    className={`item ${item.id == categoryId ? 'active' : ''}`}
                    onClick={this.categoryClick.bind(this, item.id)}
                  >{item.name}</View>)}
                </View>
                <View className='indicator' onClick={() => {
                  this.setState({isClose: !this.state.isClose})
                }}
                >
                  <AtIcon value='chevron-down' size='16' color='#777' className={`close ${isClose && 'open'}`} />
                </View>
              </View>
            </View>}
          </View>
          <Skeleton loading={loading} row={4} rowHeight={450}>
            <View className='content'>
              {(process.env.P_ENV === 'vc' || process.env.P_ENV === 'kunxin') && !!platformSet && !!platformSet.applicationOpenVip && memberAdvertisement && <AdvertisementMember url={memberAdvertisement} />}
              {type === 0 && goods.length > 0 && <GoodsBigImgList isUser={isUser} data={goods} />}
              {type === 1 && goods.length > 0 && goods.map((item, index) => <View key={item.id} className='good-item'>
                <View className='wrap' onClick={this.goDetail.bind(this, item.url)}>
                  <View className='cover'><Image src={item.main_img || item.img} mode='aspectFill' className='img' /></View>
                  <View className='info-box'>
                    <View className='title'>{item.name}</View>
                    <View className='progress' />
                    <View className='price-box'>
                      <View className='price'><Text className='symbol'>¥</Text><Text
                        className='number'
                      >{item.price}</Text><Text
                        className='market-price'
                      >¥{item.market_price}</Text></View>
                      {item.can_buy ?
                        <View className='btn'>立即购买</View>
                        :
                        <Block>
                          {platformSet.openSaleMessageSubscribe && process.env.TARO_ENV !== 'tt' ?
                            <Block>
                              <Block>
                                {item.is_subscribe ?
                                  <View className='btn disabled' onClick={this.removeMSG.bind(this, index)}>取消提醒</View> :
                                  <View className='btn' onClick={this.getMSG.bind(this, index)}>开售提醒</View>}
                              </Block>
                            </Block>
                            :
                            <View className='btn disabled'>未开始</View>
                          }
                        </Block>
                      }
                    </View>
                    {item.sell_begin_timestamp && <View className='count-down'>
                      <CountDown1 time={item.sell_begin_timestamp} onEnd={this.coutEnd.bind(this, index)} />
                    </View>}
                  </View>
                </View>
              </View>)}
              {type === 3 && goods.length > 0 && goods.map(item => <View key={item.id} className='good-item'>
                <Navigator className='wrap' url={item.url} hoverClass='none'>
                  <View className='cover'><Image src={item.main_img || item.img} mode='aspectFill' className='img' /></View>
                  <View className='info-box'
                    style='display:flex; flex-direction: column; justify-content: space-between; '
                  >
                    <View className='title'>{item.name}</View>
                    <View className='price-box'>
                      <View className='price'><Text className='symbol'>¥</Text><Text
                        className='number'
                      >{item.price}</Text><Text
                        className='market-price'
                      >¥{item.market_price}</Text></View>
                      <View className='btn end'>已经结束</View>
                    </View>
                  </View>
                </Navigator>
              </View>)}
              {goods.length === 0 && loadMoreStatus === 'noMore' && <View className='no-product'>
                <View className='icon'><Icon type='info' color={`${process.env.mainColor}`} size='93' /></View>
                <View className='tips'>提示</View>
                <Navigator url='/other/select-city/select-city'>
                  <View className='text'>暂时没有符合您条件的商品</View>
                </Navigator>
              </View>}
              {/* 广告位 */}
              <Advertisement />
            </View>
          </Skeleton>
          {linkUri && process.env.P_ENV !== 'lx' && <Share isUser={isUser} page='index' linkUri={linkUri} />}
        </View>
        <SupportBar />
      </View>
    );
  }
}

export default limitedIndex as ComponentClass<PageOwnProps, PageState>
